package org.example.buffer;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * 分散和聚集
 */
public class Demo5 {
    public static void main(String[] args) throws IOException {
        //开启ServerSocket通道
        try (ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()) {
            serverSocketChannel.bind(new InetSocketAddress(10040));
            //创建缓冲区数组
            ByteBuffer[] byteBuffers = new ByteBuffer[]{
                    ByteBuffer.allocate(5),
                    ByteBuffer.allocate(3),
            };
            //阻塞并获取Socket通道
            SocketChannel socketChannel = serverSocketChannel.accept();
            //循环
            while (socketChannel.isConnected()) {
                //读取数据
                long read = socketChannel.read(byteBuffers);
                System.out.println("read" + read);
                //打印信息
                Arrays.stream(byteBuffers).map(s -> s.position() + "|" + s.limit()).forEach(System.out::println);
                //翻转
                Arrays.stream(byteBuffers).forEach(ByteBuffer::flip);
                //写入数据
                long write = socketChannel.write(byteBuffers);
                System.out.println(write);
                //清理缓冲区
                Arrays.stream(byteBuffers).forEach(ByteBuffer::clear);
            }
        }
    }
}
